<?php


class DuitkuPay
{
    private $code;
    private $key;

    public function __construct()
    {
        $this->code = "";
        $this->key = "";
    }

    /**
     * 生成签名
     * @param array $data 待签名数据
     * @return string
     */
    private function getSign($orderId, $amount)
    {
        return md5($this->code . $orderId . $amount . $this->key);
    }

    /**
     * 使用curl发送
     * @param string $url
     * @param mixed $param
     * @return false|mixed
     */
    public function requestPost($url, $param)
    {
        $param = json_encode($param);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($param))
        );
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        $request = curl_exec($ch);
        curl_close($ch);
//        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return $result = json_decode($request, true);
//        $ch = curl_init();
//        curl_setopt($ch, CURLOPT_URL, $url);
//        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//        curl_setopt($ch, CURLOPT_SSLVERSION, 1);
//        curl_setopt($ch, CURLOPT_HEADER, 0);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//        curl_setopt($ch, CURLOPT_POST, 1);
//        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
//        $data = curl_exec($ch);
//        curl_close($ch);
//        return json_decode($data, true);
    }

    /**
     * @Notes: 创建H5支付单
     * @param $mchId
     * @param $mobilePhone
     * @param $amount
     * @param $goodsInfo
     * @param $orderNo
     * @param $callbackUrl
     * @param $notifyUrl
     * @Date: 2021/01/25 13:58
     */
    public function creatOrder($mobilePhone, $amount, $goodsInfo, $orderNo, $callbackUrl, $notifyUrl)
    {
        $url = "https://passport.duitku.com/webapi/api/merchant/v2/inquiry";
        $data = [
            'merchantCode' => $this->code,
            'paymentAmount' => $amount,
            'paymentMethod' => 'BK',
            'merchantOrderId' => $orderNo,
            'productDetails' => $goodsInfo,
            'email' => 'your@email.com',
            'phoneNumber' => $mobilePhone,
            'callbackUrl' =>$callbackUrl,
            'returnUrl' => $notifyUrl,
            'signature' => $this->getSign($orderNo,$amount)
        ];
        $res = $this->requestPost($url, $data);
        print_r($res);
    }
}